<template>
  <div class="drama-detail">
    <!-- 左侧菜单栏 -->
    <div class="drama-menu">
      <div class="menu-header">
        <div class="back-button" @click="goBack">
          <img src="@/assets/images/back-icon.png" alt="返回" class="back-icon" />
          <span class="drama-name">{{ form.dramaName }}</span>
        </div>
      </div>
      
      <div class="menu-list">
        <div 
          class="menu-item" 
          :class="{ active: currentTab === 'role' }"
          @click="switchTab('role')"
        >
          <svg-icon icon-class="jiaose" class="menu-icon" />
          <span class="menu-text">角色生成</span>
        </div>
        
        <div 
          class="menu-item" 
          :class="{ active: currentTab === 'scene' }"
          @click="switchTab('scene')"
        >
          <svg-icon icon-class="changjing" class="menu-icon" />
          <span class="menu-text">场景生成</span>
          </div>
          
        <div 
          class="menu-item" 
          :class="{ active: currentTab === 'episode' }"
          @click="switchTab('episode')"
        >
          <svg-icon icon-class="juji" class="menu-icon" />
          <span class="menu-text">剧集生成</span>
        </div>
      </div>
    </div>
    
    <!-- 右侧内容区 -->
    <div class="drama-content">
      <!-- 角色生成内容 -->
      <div v-if="currentTab === 'role'" class="section-title">角色生成</div>
      <role-management 
        v-if="currentTab === 'role'" 
        :drama-id="dramaId"
        :roles="roles"
        @update:roles="updateRoles"
      />
      
      <!-- 场景生成内容 -->
      <div v-if="currentTab === 'scene'" class="section-title">场景生成</div>
      <scene-management 
        v-if="currentTab === 'scene' && !sceneLoading && !sceneMessage" 
        ref="sceneManagementRef"
        :drama-id="dramaId"
        :scenes="scenes"
        :roles="roles"
        @update:scenes="updateScenes"
        @switch-tab="switchTab"
        @init-scene="preInitScene"
      />

      <!-- 场景生成中状态 -->
      <div v-if="currentTab === 'scene' && sceneLoading" class="scene-loading-container">
        <div class="scene-loading-content">
          <el-icon class="loading-icon"><Loading /></el-icon>
          <p class="loading-message">正在加载，请稍候...</p>
        </div>
      </div>

      <div v-if="currentTab === 'scene' && sceneMessage" class="error-message">
        <el-progress
          :stroke-width="8"
          :percentage="30"
          color="#6470FA"
          :show-text="false"
        />
        <div class="error-message-text">正在生成中，预计需要 2 小时 30 分钟，请耐心等待...</div>
      </div>
      
      <!-- 剧集生成内容 -->
       <template v-if="currentTab === 'episode'">
        <template v-if="!currentSeries">
          <div class="section-title">剧集生成</div>
          <div v-if="errorMsg" class="error-message">
            <el-progress
              :stroke-width="8"
              :percentage="currentProgress"
              color="#6470FA"
              :show-text="false"
            />
            <div class="error-message-text">{{ errorMsg }}</div>
          </div>
          <div class="empty-state" v-else-if="!hasInitStoryboard && scenes.length && roles.length">
            <img src="@/assets/images/empty.png" class="empty-image" alt="暂无场景" />
            <p class="empty-text">暂无剧集，点击下方按钮可进入预生成剧集流程</p>
            <el-button color="#1c1d29" @click="initStoryboard">预生成</el-button>
          </div>
          <episode-management 
            v-else
            :drama-id="dramaId"
            :episodes="episodes"
            :roles="roles"
            :completeLoading="episodeLoading"
            :scenes="scenes"
            @update:episodes="updateEpisodes"
            @switch-tab="switchTab"
            @select-series="handleSelectSeries"
          />
        </template>
        <!-- <template v-else>
          <StoryboardDetail @clear-series="handleClearSeries" :dramaId="dramaId" :seriesId="currentSeries.seriesId" :tab="currentSeries.imageStatus ===0 ? '1' : '2'" />
        </template> -->
       </template>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch, onUnmounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Loading } from '@element-plus/icons-vue'
import { useDramaStore } from '@/store/drama'
import { getDramaById, getDramaActor, getDramaScene, initSceneList, initAllStoryboard, checkSceneStatus, checkStoryboardStatus } from '@/api/drama'
import RoleManagement from './RoleManagement.vue'
import SceneManagement from './SceneManagement.vue'
import EpisodeManagement from './EpisodeManagement.vue'
import StoryboardDetail from './StoryboardDetail.vue'

const router = useRouter()
const route = useRoute()
const dramaStore = useDramaStore()
// 当前选中的场景
const currentSeries = ref(null)
// 获取剧本ID
const dramaId = ref(route.params.id ?? '')

// 判断当前路由
const isCreateMode = ref(route.name === 'DramaCreate')
const isEditMode = ref(route.name === 'DramaEdit')
const isViewMode = ref(route.name === 'DramaDetail')

// 当前选中的标签页，从URL参数获取或默认为'role'
const currentTab = ref(route.query.tab || 'role')

// 表单数据
const form = reactive({
  dramaName: '',
  dramaDesc: '',
  cover: null,
  members: '',
  dramaUrl: '',
  styleImages: [],
  companyName: '',
  price: '0.00',
  createTime: '',
  updateTime: '',
  dramaId: ''
})

// 剧本封面URL
const coverUrl = ref('')
const errorMsg = ref('')

// 角色、场景、分集数据
const roles = ref([])
const scenes = ref([])
const episodes = ref([])
const currentProgress = ref(0)

// 场景加载状态
const sceneLoading = ref(true)
const sceneMessage = ref('')

// 剧集轮询定时器
let episodePollingTimer = null
// 监听标签页切换
watch(currentTab, async (newTab, oldTab) => {
  errorMsg.value = ''
  
  // 如果从episode标签切换出去，停止剧集轮询
  if (oldTab === 'episode') {
    stopEpisodePolling()
  }
  
  // 更新URL参数，不刷新页面
  router.replace({
    query: { ...route.query, tab: newTab }
  })
  
  if (newTab === 'scene' && dramaId.value) {
    fetchDramaScene()
  } else if (newTab === 'episode' && dramaId.value) {
    fetchEpisodeList()
  }
})

// 监听路由参数变化
watch(() => route.query.tab, (newTab) => {
  if (newTab && newTab !== currentTab.value) {
    currentTab.value = newTab
  }
}, { immediate: true })

// 切换标签页
const switchTab = (tab) => {
  // 如果从scene标签切换出去，停止轮询
  if (currentTab.value === 'scene') {
    if (sceneManagementRef.value?.stopPolling) {
      sceneManagementRef.value.stopPolling()
    }
  }
  
  // 如果从episode标签切换出去，停止剧集轮询
  if (currentTab.value === 'episode') {
    stopEpisodePolling()
  }
  
  currentTab.value = tab
}

// 添加对场景管理组件的引用
const sceneManagementRef = ref(null)

const handleSelectSeries = (episode) => {
  currentSeries.value = episode
}

const handleClearSeries = () => {
  initData()
  currentSeries.value = null
}

// 返回上一页
const goBack = () => {
  router.push('/drama/list')
}

// 更新角色数据
const updateRoles = (newRoles) => {
  fetchDramaActor()
}

// 更新场景数据
const updateScenes = (newScenes) => {
  scenes.value = newScenes
}

// 更新分集数据
const updateEpisodes = () => {
  initStoryboard()
}

const episodeLoading = ref(true)

const initStoryboard = async () => {
  try {
    // 预拆分分镜大纲
    if (!hasInitStoryboard.value) {
      hasInitStoryboard.value = true
      await initAllStoryboard(dramaId.value)
    }
    // 状态为4，获取剧集列表
    errorMsg.value = ''
    const data = await dramaStore.fetchEpisodeList(dramaId.value)
    episodes.value = data
    episodeLoading.value = false
    
    // 检查状态
    // if (res.data && res.data.status === 4) {
      
    //   // 确保停止轮询
    //   stopEpisodePolling()
    // } else {
    //   episodeLoading.value = false
    //   // 状态不为4，显示API返回的消息
    //   errorMsg.value = res.data?.message || '剧集生成中，请稍后再试...'
    //   currentProgress.value = res.data?.percent || 0
    //   episodes.value = []
      
    //   // 开始轮询检查状态
    //   startEpisodePolling()
    // }
  } catch (error) {
    episodeLoading.value = false
    console.error('获取剧集列表失败:', error)
    errorMsg.value = error.message || '获取剧集列表失败'
    episodes.value = []
  }
}

const hasInitStoryboard = ref(true)
// 获取分集列表
const fetchEpisodeList = async () => {
  if (!dramaId.value) return
  // 检查是否拆分过分镜大纲
  const {data} = await checkStoryboardStatus(dramaId.value)
  if (data) {
    hasInitStoryboard.value = true
    initStoryboard()
  } else {
    hasInitStoryboard.value = false
  }
}

// 开始剧集轮询
const startEpisodePolling = () => {
  // 清除可能存在的之前的定时器
  stopEpisodePolling()
  
  // 设置新的定时器
  episodePollingTimer = setTimeout(async () => {
    // 只有当前标签页是episode时才继续轮询
    if (currentTab.value === 'episode') {
      try {
        // 检查初始化状态
        const res = await initAllStoryboard(dramaId.value)
        
        if (res.data && res.data.status === 4) {
          // 状态为4，获取剧集列表
          errorMsg.value = ''
          const data = await dramaStore.fetchEpisodeList(dramaId.value)
          episodes.value = data
          
          // 清除定时器
          stopEpisodePolling()
        } else {
          // 更新消息
          if (res.data && res.data.message) {
            errorMsg.value = res.data.message
          }
          // 继续轮询
          startEpisodePolling()
        }
      } catch (error) {
        console.error('检查剧集生成状态失败:', error)
        errorMsg.value = error.message || '检查剧集生成状态失败'
        // 出错也继续轮询
        startEpisodePolling()
      }
    }
  }, 15000) // 15秒轮询一次
}

// 停止剧集轮询
const stopEpisodePolling = () => {
  if (episodePollingTimer) {
    clearTimeout(episodePollingTimer)
    episodePollingTimer = null
  }
}

const dataFinished = ref(false)

// 监听数据加载
watch(dataFinished, async (data) => {
  if (dataFinished.value) episodeLoading.value = false
})

// 获取剧本演员
const fetchDramaActor = async () => {
  if (!dramaId.value) return
  try {
    const { data } = await getDramaActor(dramaId.value)
    roles.value = data || []
  } catch (error) {
    console.error('获取剧本演员失败:', error)
    ElMessage.error('获取剧本演员失败')
  }
}

// 预生成场景
const preInitScene = async () => {
  const initResponse = await initSceneList(dramaId.value)
  // 检查返回状态
  if (initResponse.data && initResponse.data.status !== 4) {
    // 显示返回的消息
    if (initResponse.data.message) {
      sceneMessage.value = initResponse.data.message
    } else {
      sceneMessage.value = '场景列表生成中，请稍候...'
    }
    
    // 开始轮询
    startPolling()
  } else {
    // 状态已经是4，直接获取场景列表
    const sceneResponse = await getDramaScene(dramaId.value)
    scenes.value = sceneResponse.data || []
    sceneMessage.value = ''
  }
}
// 获取剧本场景 
const fetchDramaScene = async () => {
  if (!dramaId.value) return
  
  try {
    sceneLoading.value = true
      // 没有场景数据，调用初始化API
    const { data } = await checkSceneStatus(dramaId.value)
    if (data) {
      await preInitScene()
    }
  } catch (error) {
    console.error('获取剧本场景失败:', error)
    ElMessage.error('获取剧本场景失败')
  } finally {
    sceneLoading.value = false
  }
}

// 轮询定时器
let pollingTimer = null

// 开始轮询
const startPolling = () => {
  // 清除可能存在的之前的定时器
  if (pollingTimer) {
    clearTimeout(pollingTimer)
  }
  
  pollingTimer = setTimeout(async () => {
    try {
      // 检查初始化状态
      const statusResponse = await initSceneList(dramaId.value)
      
      if (statusResponse.data && statusResponse.data.status === 4) {
        // 状态为4，获取场景列表
        const sceneResponse = await getDramaScene(dramaId.value)
        scenes.value = sceneResponse.data || []
        sceneMessage.value = ''
        sceneLoading.value = false
        
        // 清除定时器
        clearTimeout(pollingTimer)
        pollingTimer = null
      } else {
        // 显示返回的消息
        if (statusResponse.data && statusResponse.data.message) {
          sceneMessage.value = statusResponse.data.message
        }
        // 继续轮询
        startPolling()
      }
    } catch (error) {
      console.error('检查场景生成状态失败:', error)
      // 出错也继续轮询
      startPolling()
    }
  }, 15000) // 15秒轮询一次
}

// 停止轮询
const stopPolling = () => {
  if (pollingTimer) {
    clearTimeout(pollingTimer)
    pollingTimer = null
  }
}

// 在组件卸载时清除所有定时器
onUnmounted(() => {
  stopPolling()
  stopEpisodePolling()
})

// 暴露停止轮询方法给父组件
defineExpose({
  stopPolling,
  stopEpisodePolling
})

// 获取剧本详情
const fetchDramaDetail = async () => {
  if (!dramaId.value) return
  
  try {
    const { data } = await getDramaById(dramaId.value)
    
    if (!data) {
      throw new Error('获取剧本详情失败')
    }
    
    // 填充表单
    form.dramaName = data.dramaName || ''
    form.dramaDesc = data.dramaDesc || ''
    form.dramaUrl = data.fileUrl || ''
    form.companyName = data.companyName || ''
    form.price = data.price ? (data.price / 100).toFixed(2) : '0.00'
    form.members = data.createUser || ''
    coverUrl.value = data.coverUrl || ''
    form.createTime = data.createAt ? new Date(data.createAt).toLocaleString() : ''
    form.updateTime = data.updateAt ? new Date(data.updateAt).toLocaleString() : ''
    form.dramaId = data.dramaId || ''
  } catch (error) {
    console.error('获取剧本详情失败:', error)
    ElMessage.error('获取剧本详情失败')
    router.push('/drama/list')
  }
}

// 重置表单和状态数据
const resetFormData = () => {
  form.dramaName = ''
  form.dramaDesc = ''
  form.cover = null
  form.members = ''
  form.dramaUrl = ''
  form.styleImages = []
  form.companyName = ''
  form.price = '0.00'
  form.createTime = ''
  form.updateTime = ''
  form.dramaId = ''
  
  coverUrl.value = ''
  roles.value = []
  scenes.value = []
  episodes.value = []
}



const initData = async () => {
  // 确保每次加载组件时都重置表单数据
  resetFormData()
  episodeLoading.value = true
  
  if (isCreateMode.value) {
    // 创建模式，不需要加载数据
    form.dramaName = '新建剧本'
  } else if (dramaId.value) {
    // 编辑或查看模式，加载剧本详情
    await fetchDramaDetail()
    await fetchDramaActor()
    const sceneResponse = await getDramaScene(dramaId.value)
    scenes.value = sceneResponse.data || []
    dataFinished.value = true
    
    // 根据当前标签页加载对应的数据
    if (currentTab.value === 'scene') {
      fetchDramaScene()
    } else if (currentTab.value === 'episode') {
      fetchEpisodeList()
    }
  } else {
    // 没有ID但不是创建模式，重定向到列表页
    router.push('/drama/list')
  }
}

onMounted(async () => {
  initData()
})
</script>

<style scoped>
.section-title {
  font-size: 16px;
  color: #1f2329;
  font-weight: 500;
  margin-bottom: 16px;
}
.drama-detail {
  display: flex;
  height: 100%;
  min-height: 600px;
  background-color: var(--bg-color-light);
  border-radius: 8px;
}

/* 左侧菜单样式 */
.drama-menu {
  width: 200px;
  height: 100%;
  background-color: #fff;
  padding: 16px;
  border-right: 1px solid var(--border-color);
}

.menu-header {
  margin-bottom: 24px;
}

.back-button {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.back-icon {
  width: 16px;
  height: 16px;
  margin-right: 8px;
}

.drama-name {
  font-size: 12px;
  color: var(--text-menu);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.menu-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.menu-item {
  display: flex;
  align-items: center;
  padding: 8px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
}

.menu-icon {
  font-size: 16px;
  color: var(--text-menu);
  margin-right: 8px;
}

.menu-text {
  font-size: 14px;
  color: var(--text-menu);
}

.menu-item:hover {
  background-color: rgba(162, 166, 184, 0.08);
}

.menu-item:hover .menu-icon,
.menu-item:hover .menu-text {
  color: var(--hover-color);
}

.menu-item.active {
  background-color: var(--menu-active-bg);
}

.menu-item.active .menu-icon,
.menu-item.active .menu-text {
  color: var(--theme-color);
  font-weight: 500;
}

/* 右侧内容区样式 */
.drama-content {
  flex: 1;
  height: 100%;
  padding: 24px;
  overflow: auto;
  background-color: #F9FAFC;
}

/* 场景生成中状态样式 */
.scene-loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  width: 100%;
  padding: 20px;
}

.scene-loading-content {
  text-align: center;
  padding: 40px;
}

.loading-icon {
  font-size: 48px;
  color: var(--primary-color, #1C1D29);
  margin-bottom: 20px;
  animation: spin 2s infinite linear;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.loading-title {
  font-size: 20px;
  font-weight: 500;
  color: var(--text-title, #1C1D29);
  margin-bottom: 16px;
}

.loading-message {
  font-size: 14px;
  color: #787C8F;
  margin-bottom: 16px;
  line-height: 1.5;
}

.loading-tip {
  font-size: 14px;
  color: var(--text-secondary, #A2A6B8);
  background-color: #f5f7fa;
  padding: 8px 16px;
  border-radius: 4px;
  display: inline-block;
}
.error-message {
  width: 650px;
  margin: auto;
  padding-top: 186px;
}
.error-message-text {
  text-align: center;
  color:#787C8F;
  margin-top: 24px;
  font-size: 14px; 
}
/* 空状态样式 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 186px;
}

.empty-image {
  width: 240px;
  height: 240px;
}

.empty-text {
  font-size: 14px;
  color: #787C8F;
  margin: 20px 0;
}

/* 错误信息样式 */
</style> 